import network
import time
from lib.net.wlan import wlan_esp32


def scan_wifi():
    """扫描可用的WiFi网络"""
    print("开始扫描WiFi网络...")

    # 创建WLAN对象
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)

    # 扫描网络
    networks = wlan.scan()

    if not networks:
        print("未发现任何WiFi网络")
        return

    print(f"发现 {len(networks)} 个WiFi网络:")
    print("-" * 60)
    print(f"{'SSID':<20} {'信号强度':<10} {'加密方式':<15} {'MAC地址'}")
    print("-" * 60)

    # 按信号强度排序
    networks.sort(key=lambda x: x[3], reverse=True)

    for net in networks:
        ssid = net[0].decode("utf-8") if net[0] else "隐藏网络"
        bssid = ":".join(["%02x" % b for b in net[1]])
        channel = net[2]
        rssi = net[3]
        security = net[4]
        hidden = net[5]

        # 信号强度转换为百分比
        signal_percent = min(100, max(0, (rssi + 100) * 2))

        # 加密方式
        if security == 0:
            security_type = "开放"
        elif security == 1:
            security_type = "WEP"
        elif security == 2:
            security_type = "WPA-PSK"
        elif security == 3:
            security_type = "WPA2-PSK"
        elif security == 4:
            security_type = "WPA/WPA2-PSK"
        else:
            security_type = "未知"

        print(
            f"{ssid:<20} {signal_percent:>3}% ({rssi:>3}dBm) {security_type:<15} {bssid}"
        )

    print("-" * 60)
    return networks


def scan_wifi_continuous(interval=5):
    """持续扫描WiFi网络"""
    print(f"开始持续扫描WiFi网络，间隔 {interval} 秒")
    print("按Ctrl+C停止扫描")

    try:
        while True:
            scan_wifi()
            print(f"\n等待 {interval} 秒后进行下次扫描...\n")
            time.sleep(interval)
    except KeyboardInterrupt:
        print("\n扫描已停止")


def scan_wifi_by_strength():
    """按信号强度扫描并显示详细信息"""
    print("按信号强度扫描WiFi网络...")

    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)

    networks = wlan.scan()

    if not networks:
        print("未发现任何WiFi网络")
        return

    # 按信号强度排序
    networks.sort(key=lambda x: x[3], reverse=True)

    print(f"发现 {len(networks)} 个WiFi网络，按信号强度排序:")
    print("=" * 80)

    for i, net in enumerate(networks, 1):
        ssid = net[0].decode("utf-8") if net[0] else "隐藏网络"
        bssid = ":".join(["%02x" % b for b in net[1]])
        channel = net[2]
        rssi = net[3]
        security = net[4]
        hidden = net[5]

        signal_percent = min(100, max(0, (rssi + 100) * 2))

        # 信号强度条
        bar_length = 20
        filled_length = int(bar_length * signal_percent / 100)
        bar = "█" * filled_length + "░" * (bar_length - filled_length)

        if security == 0:
            security_type = "开放"
        elif security == 1:
            security_type = "WEP"
        elif security == 2:
            security_type = "WPA-PSK"
        elif security == 3:
            security_type = "WPA2-PSK"
        elif security == 4:
            security_type = "WPA/WPA2-PSK"
        else:
            security_type = "未知"

        print(f"{i:2d}. {ssid}")
        print(f"    信号强度: {bar} {signal_percent:3d}% ({rssi:3d}dBm)")
        print(f"    加密方式: {security_type}")
        print(f"    信道: {channel}")
        print(f"    MAC地址: {bssid}")
        print(f"    隐藏网络: {'是' if hidden else '否'}")
        print("-" * 80)


def get_wifi_info():
    """获取当前WiFi连接信息"""
    wlan = network.WLAN(network.STA_IF)

    if wlan.isconnected():
        print("当前WiFi连接信息:")
        print("=" * 40)
        ifconfig = wlan.ifconfig()
        print(f"IP地址: {ifconfig[0]}")
        print(f"子网掩码: {ifconfig[1]}")
        print(f"网关: {ifconfig[2]}")
        print(f"DNS: {ifconfig[3]}")
        print(f"主机名: {wlan.config('hostname')}")
    else:
        print("当前未连接WiFi网络")


if __name__ == "__main__":
    print("ESP32 WiFi扫描工具")
    print("=" * 40)

    # 显示当前WiFi信息
    get_wifi_info()
    print()

    # 执行扫描
    scan_wifi_by_strength()

    # 如果需要持续扫描，取消下面的注释
    # scan_wifi_continuous(10)
